package com.qianfeng.vhly.youshare.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import com.qianfeng.vhly.youshare.Constants;
import com.qianfeng.vhly.youshare.DataStorage;
import com.qianfeng.vhly.youshare.R;
import com.qianfeng.vhly.youshare.SubCategoryActivity;
import com.qianfeng.vhly.youshare.adapters.StorePlatformAdapter;
import com.qianfeng.vhly.youshare.model.Category;
import com.qianfeng.vhly.youshare.model.Product;
import com.qianfeng.vhly.youshare.tasks.ProductListTask;
import com.qianfeng.vhly.youshare.tasks.TaskProcessor;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: vhly[FR]
 * Date: 15/2/5
 * Email: vhly@163.com
 */
public class StorePlatformFragment extends Fragment implements TaskProcessor, AdapterView.OnItemClickListener {

    /**
     * 设置分类部分一行显示几个，需要代码进行设置，同时进行显示个数的管理
     */
    public static final int NUM_COLUMN = 3;
    private boolean hasFirstLoad;

    private List<Product> products;
    private StorePlatformAdapter adapter;
    /**
     * 子分类ID，如果这个id没有设置，那么就显示的是 平台商品列表，
     * 就需要包含分类九宫格，如果设置了,那么就是显示特定的分类下的商品列表
     * 不需要显示分类九宫格了。
     */
    private String categoryId;

    public StorePlatformFragment() {
        // Default constructor do not delete this method.
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        products = new LinkedList<Product>();

        Bundle arguments = getArguments();
        if (arguments != null) {
            categoryId = arguments.getString(Constants.ARG_SUB_CATEGORY_ID);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View ret = inflater.inflate(R.layout.fragment_store_platform, container, false);

        ///////// 商品部分九宫格界面 ///////////
        GridView gridView = (GridView) ret.findViewById(R.id.store_platform_products);

        // 设置Adapter
        adapter = new StorePlatformAdapter(getActivity(), products);

        gridView.setAdapter(adapter);

        // 分类部分九宫格界面

        GridView categoryView = (GridView) ret.findViewById(R.id.store_platform_categories);
        // 由于分类没有图片，因此我们可以使用自己定义的图片进行设置，既然采用本地资源图片
        // 就可以采用SimpleAdapter

        if (categoryView != null) {

            // 如果有分类ID，那么隐藏
            if(categoryId != null){
                categoryView.setVisibility(View.GONE);
            }

            categoryView.setOnItemClickListener(this);

            // 设置分类九宫格一行显示的个数
            categoryView.setNumColumns(NUM_COLUMN);


            List<Map<String, Object>> data
                    = new LinkedList<Map<String, Object>>();

            DataStorage dataStorage = DataStorage.getInstance();

            Category category = dataStorage.getCategory("2");// 平台产品 id 为 2

            if (category != null) {
                List<Category> subCategories = category.getSubCategories();

                // 检查GridView一行显示几个，根据当前的数量进行一个运算，显示整行
                // 一行几个
                int numColumns = NUM_COLUMN;
                int size = subCategories.size();

                int row = size / numColumns;
                int cc = size % numColumns;

                int realCount = 0;

                if (row > 0) {
                    realCount = row * numColumns;
                }

                int count = 0;

                // 设置SimpleAdapter的数据，用于显示分类
                for (Category subCategory : subCategories) {
                    count++;
                    if (count > realCount) {
                        break;
                    }
                    String name = subCategory.getName();

                    String id = subCategory.getId();

                    // TODO 根据ID设置图片 icon



                    HashMap<String, Object> map = new HashMap<String, Object>();

                    map.put("title", name);

                    map.put("icon", R.drawable.ic_launcher);

                    data.add(map);

                }
            }

            SimpleAdapter categoryAdapter
                    = new SimpleAdapter(
                    getActivity(),
                    data,
                    R.layout.item_platform_category,
                    new String[]{"icon", "title"},
                    new int[]{R.id.item_category_icon, R.id.item_category_title}
            );

            categoryView.setAdapter(categoryAdapter);

        }

        if (!hasFirstLoad) {
            ProductListTask task = new ProductListTask(this);

            String cid = "2";

            // 如果需要显示特定分类下的商品，那么就是用 categoryId
            // 否则 就是 2 －》 “平台产品”
            if(categoryId != null){
                cid = categoryId;
            }

            task.execute(cid, "10");
        }

        return ret;
    }

    @Override
    public void processResult(JSONObject result) {
        hasFirstLoad = true;
        if (result != null) {
            try {
                int code = result.getInt("code");

                if (code == 1) {
                    // TODO 正确数据，需要解析

                    JSONObject msg = result.getJSONObject("msg");

                    JSONObject data = msg.getJSONObject("data");

                    Iterator keys = data.keys();

                    List<Product> productList = new LinkedList<Product>();

                    while (keys.hasNext()) {
                        Object key = keys.next();
                        JSONObject jsonObject = data.getJSONObject((String) key);
                        Product product = new Product();
                        product.parseJSON(jsonObject);
                        productList.add(product);
                    }

                    // 注意，如果是刷新数据，那么products成员变量就需要清空，然后
                    //      用productList里面的内容添加到 products中，相当于ListView重新加载
                    // 如果需要实现，“加载更多”的操作，那么就不能够清空 List，而是直接添加


                    products.addAll(productList);

                    adapter.notifyDataSetChanged();

                } else {
                    String msg = result.getString("msg");
                    Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // TODO 商品分类点击

        int parentId = parent.getId();
        // 点击的是 分类
        if(parentId == R.id.store_platform_categories){
            DataStorage dataStorage = DataStorage.getInstance();

            //
            Category category = dataStorage.getCategory("2");

            if (category != null) {
                List<Category> subCategories = category.getSubCategories();

                // 取子分类

                Category cat = subCategories.get(position);

                String catId = cat.getId();

                Intent intent = new Intent(getActivity(), SubCategoryActivity.class);

                intent.putExtra(Constants.INTENT_KEY_CATEGORY_ID, catId);

                startActivity(intent);

            }
        }


    }
}